package com.getpebble.android.util;

import com.getpebble.android.PebbleApplication;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.util.Locale;
import java.util.MissingResourceException;

public class LocaleUtil {
    private static final String TAG = LocaleUtil.class.getSimpleName();

    public static String getLanguageForDevice(PblDeviceRecord record) {
        if (record == null) {
            return "";
        }
        if (record.isoLocale == null) {
            return "";
        }
        Trace.debug(TAG, "Language tag: " + record.isoLocale);
        try {
            Locale locale = parseLocale(record.isoLocale);
            if (isKnownLanguageName(locale)) {
                return locale.getDisplayLanguage(locale);
            }
            Trace.debug(TAG, "Locale does not have known language name");
            return "";
        } catch (IllegalArgumentException e) {
            Trace.debug(TAG, "Failed to parse locale " + record.isoLocale);
            return "";
        }
    }

    static Locale parseLocale(String locale) throws IllegalArgumentException {
        String[] parts = locale.split("_");
        switch (parts.length) {
            case SMTPMessage.RETURN_FULL /*1*/:
                return new Locale(parts[0]);
            case SMTPMessage.RETURN_HDRS /*2*/:
                return new Locale(parts[0], parts[1]);
            case ListInfo.INDETERMINATE /*3*/:
                return new Locale(parts[0], parts[1], parts[2]);
            default:
                throw new IllegalArgumentException("Invalid locale: " + locale);
        }
    }

    static boolean isKnownLanguageName(Locale locale) {
        try {
            return (locale.getISO3Language() == null || locale.getISO3Country() == null) ? false : true;
        } catch (MissingResourceException e) {
            return false;
        }
    }

    public static String getCurrentLocaleTag() {
        Locale currentLocale = getCurrentLocale();
        Trace.debug(TAG, "Retrieved current locale: " + currentLocale);
        return PblLocale.from(currentLocale).getLocale();
    }

    private static Locale getCurrentLocale() {
        return PebbleApplication.getAppContext().getResources().getConfiguration().locale;
    }
}
